Vue.component('jwb-dialog', {
  template: '<el-dialog class="c-jdialog" ref="thedialog"' +
            '  :title="title"' +
            '  :visible.sync="dialogVisible"' +
            '  :width="width"' +
            '  :fullscreen="fullscreen"' +
            '  :close-on-click-modal="false"' +
            '  @close="handleClose">' +
            '  <iframe class="c-jdialog-frame" :src="url" frameborder="0" framespacing="0" @load="onFrameLoad()"></iframe>' +
            '  <div v-show="frameLoading==true" class="w-dialoading"><span>加载中...</span></div>' +
            '</el-dialog>',  
  props: {
  },
  data: function () {
    return {
      dialogVisible: false,
      url: "about:blank",
      title: "",
      fullscreen: false,
      width: "",
      height: "",
      closeData: null,
      frameLoading: true
    }
  }, 

  mounted: function(){
    var that = this;
    //console.log(this.$refs.thedialog)
    window.addEventListener("message", function(event){
        //console.log(event.data);
        var s = event.data.toString();
        
        //点了某个按钮或者其他操作, 调用了postmsg, 但是窗口不会马上关闭, 等关闭的时候再调用callback
        if(s.indexOf("jwb-dialog-data-change") == 0) {
          s = s.replace("jwb-dialog-data-change-", "");
          that.closeData = s;
        }
        
        // 弹出的页面 点了某一个按钮或者其他操作 调用了postMessage 然后马上触发callback 然后关闭页面
        else if (s.indexOf("jwb-dialog-close") == 0) {
          try {
            if(s.indexOf("jwb-dialog-close-change") == 0 && that.callback) {
              s = s.replace("jwb-dialog-close-change-", "");
              that.callback(s); 
              that.closeData = null;
            }
          }catch(e){console.log(e)}
          that.dialogVisible = false;
        }

    }, false);    
  },
  methods: {
    onFrameLoad: function() {
      this.frameLoading = false;
    },
    handleClose: function() {
      if(this.closeData) {
        this.callback(this.closeData);
      }
      this.reset();
    },
    reset: function() {
      this.url = "about:blank";
      this.title = "";
      this.isFullScreen = false;
      this.callback = null;
      this.closeData = null;
      var that = this;
      // 如果用closed事件 下面的代码无效, 但是使用close事件,界面会看到重置的动作,所以只能延时执行
      setTimeout(function(){
        that.width = "";
        $(that.$refs.thedialog.$el).find(".el-dialog").height("");  
        that.frameLoading = true;      
      }, 500);
    },
    open: function(aUrl, arg) {
      arg = arg || {};
      this.url = aUrl;
      arg.title && (this.title = arg.title);
      arg.fullscreen && (this.fullscreen = arg.fullscreen);
      arg.callback && (this.callback = arg.callback);
      if(!arg.fullscreen) {
        arg.width && (this.width = arg.width);
        var h = arg.height || 400;
        $(this.$refs.thedialog.$el).find(".el-dialog").height(h);
      }
      this.dialogVisible = true;
    }
  }
})